<?php

// +----------------------------------------------------------------------
// | Think.Admin
// +----------------------------------------------------------------------
// | 版权所有 2014-2018 东莞市云拓互联网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站:http://www.ytclouds.net
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/Think.Admin
// +----------------------------------------------------------------------

namespace app\webapi\controller;

use app\webapi\controller\Baseapp;
use app\webapi\service\LotteryService;
use service\DataService;
use think\Db;
use app\webapi\service\AppuserService;
use service\DysmsService;

/**
 * @package app\store\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/27 14:43
 */
class User extends Baseapp
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $table = 'AppUsers';

    /**
     * 获取用户基本信息
     */
    public function get_userinfo()
    {
        $user_info = AppuserService::get_user_data($this->user_id, "*");
        return $this->fetch('', ['user_info' => $user_info]);
    }

    /**
     * 用户信息
     * @return mixed
     */
    public function user_center()
    {
        $user_info = AppuserService::get_user_data($this->user_id, "*");
        return $this->fetch('', ['user_info' => $user_info]);
    }

    /**
     * 用户报名
     */
    public function user_form()
    {
        $form_data = Db::name('CompetitionSignUp')
            ->where(['user_id' => $this->user_id, 'competition_id' => 1])
            ->find();
        //获取文章规则
        $articles = Db::name("Article")
            ->where('id','in','1,2')
            ->select();

        $this->assign("article",$articles);
        return $this->fetch('', ["vo" => $form_data ]);
    }

    /**
     * 用户报名
     */
    public function my_form()
    {
        $form_data = Db::name('CompetitionSignUp')
            ->where(['user_id' => $this->user_id, 'competition_id' => 1])
            ->find();
        return $this->fetch('', ["vo" => $form_data]);
    }

    /**
     * 更新用户表单信息
     */
    public function update_form()
    {
        header('Content-Type:application/json; charset=utf-8');
        $status = $this->success_code;
        $data = $this->request->post();
        $update = [];
        $form_data = Db::name('CompetitionSignUp')
            ->where(['user_id' => $this->user_id, 'competition_id' => 1])
            ->find();
        if ($form_data) {
            $update['id'] = $form_data['id'];
        }
        $update['competition_id'] = 1;
        $update['user_id'] = $this->user_id;
        //插入数据
        if($data['form'] == 'user_form'){
            if (isset($data['userName'])) {
                $update['name'] = $data['userName'];
            }
            if (isset($data['sex'])) {
                $update['sex'] = $data['sex'];
            }
            if (isset($data['phone'])) {
                $update['phone_num'] = $data['phone'];
            }
            $code = '';
            if (isset($data['code'])) {
                $code = $data['code'];
            }
            //验证手机号和验证码
            $check_code = $this->check_code($update['phone_num'],$code);
            if(!$check_code){
                $arr = [
                    'status' => -1,
                    'msg' => '短信验证码错误',
                    'result' => ''
                ];
                $this->json_return($arr);
            }

            if (isset($data['identityNum'])) {
                $update['identity_num'] = $data['identityNum'];
            }
            if (isset($data['joinKind'])) {
                $update['join_kind'] = implode(',',$data['joinKind']);
            }
            if (isset($data['joinType'])) {
                $update['join_type'] = $data['joinType'];
            }
            if (isset($data['groupName'])) {
                $update['group_name'] = $data['groupName'];
            }
            if (isset($data['groupNum'])) {
                $update['group_num'] = $data['groupNum'];
            }
            if (isset($data['is_possess_music'])) {
                $update['is_possess_music'] = $data['is_possess_music'];
            }
            if (isset($data['is_original'])) {
                $update['is_original'] = $data['is_original'];
            }
            if (isset($data['match_type'])) {
                $update['match_type'] = $data['match_type'];
            }
            if (isset($data['groupType'])) {
                $update['group_type'] = $data['groupType'];
            }
            if (isset($data['music_instruments'])) {
                $update['music_instruments'] = $data['music_instruments'];
            }
        }

        if($data['form'] == 'user_form1'){
            if (isset($data['birthday'])) {
                $update['birthday'] = $data['birthday'];
            }
            if (isset($data['height'])) {
                $update['height'] = $data['height'];
            }
            if (isset($data['weight'])) {
                $update['weight'] = $data['weight'];
            }
            if (isset($data['unit'])) {
                $update['company'] = $data['unit'];
            }
            if (isset($data['nationality'])) {
                $update['nationality'] = $data['nationality'];
            }
            if (isset($data['like'])) {
                $update['hobby'] = $data['like'];
            }
            if (isset($data['address'])) {
                $update['address'] = $data['address'];
            }
            if (isset($data['urgency'])) {
                $update['emergency_contact_phone'] = $data['urgency'];
            }
            if (isset($data['is_broker'])) {
                $update['broker'] = $data['is_broker'];
            }
            if (isset($data['joinExperience'])) {
                $update['competition_experience'] = $data['joinExperience'];
            }
            if (isset($data['gainAward'])) {
                $update['award_experience'] = $data['gainAward'];
            }
            if (isset($data['area'])) {
                $update['province'] = isset($data['area']['province'])?$data['area']['province']:'';
                $update['city'] = isset($data['area']['city'])?$data['area']['city']:'';
                $update['county'] = isset($data['area']['county'])?$data['area']['county']:'';
            }
        }

        $r = DataService::save('CompetitionSignUp', $update, 'id');
        if($r){
            $arr = [
                'status' => $status,
                'msg' => '保存成功',
                'result' => ''
            ];
            //报名成功增加次数
            AppuserService::do_apply($this->user_id);
        }else{
            $arr = [
                'status' => 400,
                'msg' => '保存失败',
                'result' => ''
            ];
        }
        $this->json_return($arr);
    }

    /**
     * 用户缴费
     */
    public function pay()
    {
        $user_form = Db::name("competition_sign_up")
            ->where(['competition_id'=>1,'user_id'=>$this->user_id])
            ->field("match_type")
            ->find();
        $match_type = [];
        if(isset($user_form['match_type']) && $user_form['match_type']){
            $match_type = explode(',',$user_form['match_type']);
        }
        $products = Db::name("Products")
            ->where(['status'=>1,'is_deleted'=>0])
            ->select();
        foreach ($products as $k => &$v){
            if(in_array($v['goods_title'],$match_type)){
                $v['is_checked'] = 1;
            }else{
                $v['is_checked'] = 0;
            }
        }
        $this->assign('products', $products);
        return $this->fetch('');
    }

    /**
     * 用户报名2， 资料补充
     */
    public function user_form2()
    {
        $form_data = Db::name('CompetitionSignUp')
            ->where(['user_id' => $this->user_id, 'competition_id' => 1])
            ->find();
        $this->assign('vo', $form_data);
        return $this->fetch('');
    }

    /**
     * 我的中奖列表
     * @return mixed
     */
    public function my_lottery()
    {
        $res = LotteryService::get_my_pool($this->user_id);
        $my_pool = [];
        foreach ($res as $key => $val) {
            $my_pool[$key]['title'] = $val['good_name'];
            $my_pool[$key]['img'] = $val['original_img'];
            $my_pool[$key]['desc'] = $val['copywriter2'];
            $my_pool[$key]['href'] = $val['href'];
            $my_pool[$key]['date'] = date("Y-m-d", $val['addtime']);
        }

        /*$my_pool = [
            [
                'title' => 'Ofo小黄单车月卡',
                'desc' => '有效期为2018-02-12至2018-2-2，逾期作废!',
                'img' => '/static/webapp/images/test.jpg',
                'href' => 'http://www.ofo.so',
                'date'=>'2018-2-2'
            ]
        ];*/

        $this->assign('my_pool', $my_pool);

        return $this->fetch('');
    }

    /**
     * 用户分享操作
     */
    public function user_share()
    {
        AppuserService::do_share($this->user_id);
    }

    /**
     * 用户缴费记录
     */
    public function payHistory()
    {
        $res = Db::name('Order')
            ->where(['user_id'=>$this->user_id,'is_pay'=>1])
            ->select();
        foreach ($res as $k => &$v){
            $join = [
                ['products p', 'og.product_id=p.id'],
            ];
            $fields = "og.*,p.goods_title,p.prices";
            $order_goods = Db::name('OrderGoods')
                ->alias("og")
                ->join($join)
                ->where("og.order_id = ".$v['id']."")
                ->field($fields)
                ->select();
            $v['order_goods'] = $order_goods;
        }

        $this->assign("res",$res);
        return $this->fetch('');
    }

    /**
     * 关于我们
     */
    public function about_us()
    {
        $articles = Db::name("Article")
            ->where('id','4')
            ->find();

        $this->assign("article",$articles);
        return $this->fetch('');
    }

    /**
     * 亚音介绍
     */
    public function intro()
    {
        $articles = Db::name("Article")
            ->where('id','3')
            ->find();

        $this->assign("article",$articles);
        return $this->fetch('');
    }


    public function check_code($modile,$code){
        if(!$modile||!$code){
            return false;
        }
        $table = "SmsLog";
        $r = DB::name($table)
            ->where("phone",$modile)
            ->where("code",$code)
            ->where("is_used",0)
            ->find();
        if($r){
            Db::name($table)
                ->where("phone",$modile)
                ->where("code",$code)
                ->data(['is_used'=>1])
                ->update();
            return true;
        }
        return false;
    }


    /**
     * 短信发送
     */
    public function send_sms(){
        $table = "SmsLog";
        $nowtime = time();
        $get = $this->request->get();
        if(!isset($get['mobile'])){
            $arr = [
                'status' => -1,
                'msg' => '参数错误',
                'result' => ''
            ];
            $this->json_return($arr);
        }
        if(!$this->user_id){
            $arr = [
                'status' => -2,
                'msg' => '请重新登录',
                'result' => ''
            ];
            $this->json_return($arr);
        }
        //验证是否吃鸡
        $laster_one = Db::name($table)
            ->where(['user_id'=>$this->user_id])
            ->order("create_at desc")
            ->find();
        if($laster_one){
            $formate_time = strtotime($laster_one['create_at']);
            if(($nowtime - $formate_time)<60){
                $arr = [
                    'status' => -3,
                    'msg' => '请不要频繁发送短信',
                    'result' => ''
                ];
                $this->json_return($arr);
            }
        }
        $mobile = $get['mobile'];
        $laster = Db::name($table)
            ->where(['phone'=>$mobile])
            ->order("create_at desc")
            ->find();
        if($laster){
            $formate_time = strtotime($laster['create_at']);
            if(($nowtime - $formate_time)<60){
                $arr = [
                    'status' => -3,
                    'msg' => '请不要频繁发送短信',
                    'result' => ''
                ];
                $this->json_return($arr);
            }
        }
        //生成CODE
        $DysmsService = new DysmsService();
        $code = $DysmsService->create_code();
        $r = $DysmsService->sendSMS($mobile,$code);
//        $r = 1;
        //操作保存数据
        if($r){
            //录入数据库
            $insert = [];
            $insert['phone'] = $mobile;
            $insert['code'] = $code;
            $insert['user_id'] = $this->user_id;
            $insert['is_used'] = 0;
            Db::name($table)->insert($insert);
            $arr = [
                'status' => 200,
                'msg' => '发送成功',
                'result' => ''
            ];
            $this->json_return($arr);
        }else{
            $arr = [
                'status' => -4,
                'msg' => '发送短信失败，请稍后重试',
                'result' => ''
            ];
            $this->json_return($arr);
        }
    }

}
